#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
#include <string.h>
#include <errno.h>


static void print_err(char *str, int line, int err_no) {
    if (str != NULL) {
        printf("line %d %s: %s\n", line, str, strerror(err_no));
        exit(-1);
    }
}


int mousefd = -1;

void signal_fun(int signo) {
    if (signo == SIGIO) {
        int buf = 0;
        int ret = read(mousefd, &buf, sizeof buf);
        if (ret < 0) print_err("read fail", __LINE__, errno);
        else{
            printf("%d\n", buf);
        }
    }
}

/**
 * 异步IO例程: 阻塞读取键盘数据, 异步IO读取鼠标数据
 */
int main() {
    mousefd = open("/dev/input/mouse1", O_RDONLY);
    if (mousefd < 0) print_err("open mouse file fail", __LINE__, errno);
    
    // 设置SIGIO信号捕获函数
    signal(SIGIO, signal_fun);

    // 告诉鼠标驱动: 当前进程接收并处理SIGIO信号
    fcntl(mousefd, F_SETOWN, getpid());

    // 设置当前进程读鼠标为异步IO方式
    int flags = fcntl(mousefd, F_GETFL);
    flags |= O_ASYNC;
    fcntl(mousefd, F_SETFL, flags);

    char buf[100];
    while (1) {
        memset(buf, 0, sizeof buf);
        int n = read(STDIN_FILENO, buf, sizeof buf);
        if (n < 0) print_err("read 0 fail", __LINE__, errno);
        else {
            printf("%s\n", buf);    
        }
    }

    return 0;
}



